package com.xie.authority_system.config.security.filter;

import com.xie.authority_system.config.redis.RedisService;
import com.xie.authority_system.config.security.CustomerUserDetailsService;
import com.xie.authority_system.config.security.exception.CustomAuthenticationException;
import com.xie.authority_system.config.security.handler.LoginFailureHandler;
import com.xie.authority_system.utils.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author 谢金成
 * @date 2024/1/16 15:54
 */
@Data
@Component
public class CheckTokenFilter extends OncePerRequestFilter {

    /**
     * 登录请求地址
     */
    @Value("${request.login.url}")
    private String loginUrl;

    @Autowired
    private RedisService redisService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private CustomerUserDetailsService customerUserDetailsService;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            // 获取当前请求的url地址
            String url = request.getRequestURI();
            // 当前请求是否是登录请求, 如果不是登录请求, 则需要验证token
            if (!url.equals(loginUrl)) {
                // 进行token认证
                this.validateToken(request);
            }
        } catch (AuthenticationException e) {
            loginFailureHandler.onAuthenticationFailure(request, response, e);
        }
        // 登录请求不需要token, 可以直接放行
        doFilter(request, response, filterChain);
    }

    /**
     * 认证token信息
     *
     * @param request
     */
    private void validateToken(HttpServletRequest request) {
        // 获取前端提交过来的token信息
        // 从headers头部获取token信息
        String token = request.getHeader("token");
        // 如果请求头部没有token, 那么从请求参数中获取token
        if (ObjectUtils.isEmpty(token)) {
            token = request.getParameter("token");
        }

        // 如果请求参数中也没有携带token, 则抛出异常
        if (ObjectUtils.isEmpty(token)) {
            throw new CustomAuthenticationException("token不存在");
        }

        // 判断redis中是否存在token信息
        String tokenKey = "token_" + token;
        String redisToken = redisService.get(tokenKey);
        // 判断redis是否存在token信息, 如果为null则表示token已经失效了
        if (ObjectUtils.isEmpty(redisToken)) {
            throw new CustomAuthenticationException("token已过期");
        }

        // 如果存在token, token与redisToken不一致, 则验证失败
        if (!token.equals(redisToken)) {
            throw new CustomAuthenticationException("token认证失败");
        }

        // 从token中解析出用户名
        String username = jwtUtils.getUsernameFromToken(token);
        // 判断用户名是否为空
        if (ObjectUtils.isEmpty(username)) {
            throw new CustomAuthenticationException("token解析失败");
        }
        // 获取用户信息
        UserDetails userDetails = customerUserDetailsService.loadUserByUsername(username);
        // 判断用户信息是否为空
        if (ObjectUtils.isEmpty(userDetails)) {
            throw new CustomAuthenticationException("token验证失败");
        }

        // 创建用户身份认证对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        // 设置请求信息
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        // 将验证信息交给Spring Security上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}
